from django.conf import settings
from django.db.models import Q
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from rest_framework.viewsets import ModelViewSet

from article.models import *
from article.serializer import *
from rest_framework.pagination import PageNumberPagination
# Create your views here.
from rest_framework.generics import ListAPIView,CreateAPIView
#频道目录列标分页器
from backend.libs.upyun import up
from backend.utils.nowTime import nowtime


class Mypage(PageNumberPagination):
    page_query_param = 'page'  # 第几页
    page_size_query_param = 'pagesizae'  # 一页几个
    max_page_size = 100  # 每页多100条数据
    page_size = 10 #默认多少条
#频道列标
class ChannelsListview(ListAPIView):
    queryset = Channel.objects.all()
    serializer_class = Channelserializer
    pagination_class = Mypage
#频道文章详细分页面器
class ArticleView(ListAPIView):
    queryset = Article.objects.all()
    serializer_class = Articledeatilsserializer
    pagination_class = Mypage
    def get_queryset(self):
        id = self.kwargs.get('id')
        if not id:
            return self.queryset.all()
        queryset=self.queryset.filter(channel_id=id)
        return queryset
#收藏选项
class ArticlecollectView(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = Articlecollectserialieze
    def get_queryset(self,):
        pk=self.kwargs.get('pk')
        queryset=self.queryset.filter(pk=pk)
        return queryset
#文章详情
from rest_framework.generics import RetrieveAPIView
class ArticlelistView(RetrieveAPIView):
    queryset = Article.objects.all()
    serializer_class =ArticleAllInfoserializer
    def get_queryset(self,):
        pk=self.kwargs.get('pk')
        queryset=self.queryset.filter(pk=pk)
        return queryset
class LabelView(ListAPIView):
    queryset = Label.objects.all()
    serializer_class = Lableserializer


class UploadEditorImg(View):

    def post(self, request):

        file = request.FILES.get('upload')

        img_name = nowtime + file.name

        try:
            up.put(f'/tensquare/img/{img_name}', file.read())
        except Exception as e:
            return JsonResponse({
                'message': '上传失败',
            }, status=400)

        return redirect(settings.UPYUN_BASE_URL + img_name)


class UploadAvatar(View):

    def post(self, request):

        file = request.FILES.get('img')

        img_name = nowtime + file.name

        try:
            up.put(f'/tensquare/img/{img_name}', file.read())
        except Exception as e:
            print(e)
            return JsonResponse({
                'message': '上传失败',
            }, status=400)

        return JsonResponse({'imgurl':settings.UPYUN_BASE_URL + img_name})



#发布文章
class ArticlePubView(CreateAPIView):
   queryset = Article.objects.all()
   serializer_class = ArticlePubserialieze
   def create(self, request, *args, **kwargs):
       user_id=self.request.user.id
       request.data['user_id']=user_id
       channel_id=request.data.pop('channel')
       request.data['channel_id'] = channel_id
       labels=request.data.pop('labels')
       # channel=Channel.objects.get(id=channel_id)
       articleid=Article.objects.create(**request.data)
       articleid.labels.add(*labels)
       return JsonResponse({'articleid':articleid.id,'message':'ok','success':True})
#添加评论
class ArticlecommentView(ModelViewSet):
     queryset = Comment.objects.all()
     serializer_class = Commetserializer
     def get_queryset(self,):
            pk=self.kwargs.get('pk')
            queryset=self.queryset.filter(pk=pk)
            return queryset


     def create(self, request, *args, **kwargs):
         user_id=self.request.user.id
         request.data['user_id'] = user_id
         request.data.pop('article')
         article_id=self.kwargs.get('pk')
         request.data['article_id']=article_id
         if not request.data.get('parent'):
            comment=Comment.objects.create(**request.data)
            return JsonResponse({'articleid': comment.article_id, 'message': 'ok', 'success': True})
         parent_id=request.data.pop('parent')
         request.data['parent_id']=parent_id
         comment = Comment.objects.create(**request.data)
         return JsonResponse({'articleid': comment.article_id, 'message': 'ok', 'success': True})
#搜索文章
class ArticlesearchView(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = Articleserchserializer
    pagination_class = Mypage
    def get_queryset(self):
        text= self.request.query_params.get('text')
        queryset = self.queryset.filter(Q(title__contains=text) | Q(content__contains=text))
        return queryset